from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template
from info import redis_store

@index_blu.route('/')
@user_login_data
def index():
    # 获取到当前登录用户的id
    user = g.user
    news_category=None
    news_click=None
    #新闻点击排行
    try:
        news_click=News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 查询新闻分类
    try:
        news_category=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    data={'user':user.to_dict() if user else None,'news_click':news_click,'news_category':news_category}
    return render_template('index.html',data=data)

@index_blu.route("/favicon.ico")
def get_web_icon():
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route('/news_list')
def new_list():
    # 1. 接收参数，前端发送通过get参数发送
    data_dict = request.args
    page=data_dict.get('page',1)#当前页数
    cid=data_dict.get('cid',1)#新闻分类id
    per_page=data_dict.get('per_page',5)#每页的数据
    try:
        page=int(page)
        cid=int(cid)
        per_page=int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2, 查询数据库　查询ｎｅｗｓ表　　条件　　排序　　　分页
    filter=[]
    if cid!=1:
        filter.append(News.category_id==cid)
    try:
        paginate=News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page)
        items=paginate.items
        print(items)
        totalPage=paginate.pages   #总页数
        currentPage=paginate.page   #当前页
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败',)
    newsList=[]
    for news in items:
        newsList.append(news.to_basic_dict())
    return jsonify(errno=RET.OK, errmsg="OK", newsList=newsList,totalPage=totalPage,currentPage=currentPage)


